package ci.web.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * mime-util
 * @author zhh
 */
public class MimeUtil {
    //未知情况
	public static final String UNKNOWN_MIME_TYPE = "application/octet-stream";
	//文件夹情况
	public static final String DIRECTORY_MIME_TYPE = "application/directory";
	/**
	 * 获取文件mime
	 * @param file
	 * @return
	 */
	public static String getMimeType(File file) {
		if (file.isDirectory()) {
			return DIRECTORY_MIME_TYPE;
		}
		return getMimeType(getExtension(file));
	}
	/**
	 * 根据文件扩展类型 获取  mime配置
	 * @param fileExtend
	 * @return
	 */
	public static String getMimeType(String fileExtend) {
		if (mimeTypes == null) {
			mimeTypes = new Properties();
			try(InputStream in = MimeUtil.class
					.getResourceAsStream("MimeTypes.properties")){
				mimeTypes.load(in);
			}catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
		return mimeTypes.getProperty(fileExtend, UNKNOWN_MIME_TYPE);
	}
	
	private static Properties mimeTypes = null;
	
	/**
	 * 获取文件名的扩展类型
	 * @param file
	 * @return
	 */
	public static String getExtension(File file) {
		return getExtension(file.getName());
	}
	/**
	 * 获取文件名的扩展类型
	 * @param fileName
	 * @return
	 */
	public static String getExtension(String fileName) {
		if (fileName==null || fileName.isEmpty()) {
			return "";
		}
		int index = fileName.lastIndexOf(".");
		return index < 0 ? fileName : fileName.substring(index + 1);
	}

}
